package com.qingyun.common.utils;

import com.baidu.aip.speech.AipSpeech;
import com.baidu.aip.speech.TtsResponse;
import com.baidu.aip.util.Util;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;

/**
 * @Classname BaiduMp3Service
 * @Author dyh
 * @Date 2021/10/20 15:47
 */
@Service
@Slf4j
public class BaiduMp3Util {

	@Autowired
	private AipSpeech client;

	public String generate(String context,String outPath,String per){
		// 设置可选参数
		HashMap<String, Object> options = new HashMap<String, Object>();
		options.put("spd", "5");
		options.put("pit", "5");
		options.put("per", per);
		// 调用接口
		TtsResponse res = client.synthesis(context, "zh", 1, options);
		byte[] data = res.getData();
		JSONObject res1 = res.getResult();
		if (data != null) {
			try {
				Util.writeBytesToFileSystem(data, outPath);
				return outPath;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (res1 != null) {
			log.info(res1.toString(2));
		}
		return null;
	}

}
